<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Account extends CI_Controller {
    public function index() {
        redirect(base_url().'account/profile','refresh');
    }
    
    public function design()
    {
        $this->template->set_layout('orpms');
        $this->template->set_partial('styles','partials/styles');
        $this->template->set_partial('scripts_a','partials/scripts_a');
        $this->template->set_partial('header','partials/header');
        $this->template->set_partial('subnav','partials/subnav');
        $this->template->set_partial('search','partials/search');
        $this->template->set_partial('navigation','partials/navigation');
        $this->template->set_partial('scripts_b','partials/scripts_b');
        $this->template->set_partial('footer','partials/footer');
    }
    
    public function login() {
        if($this->session->userdata('username')) {
            redirect(base_url().'account/profile?id='.$this->session->userdata('account_id'),'refresh');
        } else {
            $this->template->set_layout('orpms');
            $this->template->title('Account Login - ORPMS');
            
            $this->template->set_partial('styles','partials/styles');
            $this->template->set_partial('scripts_a','partials/scripts_a');
            $this->template->set_partial('header','partials/header');
            $this->template->set_partial('subnav','partials/subnav');
            $this->template->set_partial('scripts_b','partials/scripts_b');
            $this->template->set_partial('footer','partials/footer');
            
            //Build
            $this->template->build('pages/account/login');
        }
    }
    
    public function friends() {
        if($this->session->userdata('username')) {
            if(!isset($_GET['page'])) {
                redirect(base_url().'account/friends?page=1','refresh');
            }
            
            $select = array('account_id','f_name','l_name','about_me','avatar');
            $table = array('tbl_account','tbl_profile','tbl_friend');
            $where[0] = array('tbl_profile.profile_id','=','tbl_account.profile_id',' AND ');
            $where[1] = array('tbl_account.account_id','=',"if(UserA=".$this->session->userdata('account_id').",UserB,UserA)",' AND ');
            $where[2] = array('UserB','=',$this->session->userdata('account_id'),' OR ','UserA','=',$this->session->userdata('account_id'),' AND ');
            $where[3] = array('tbl_friend.status','=',1);
            $sortby = 'CONCAT(f_name,l_name)';
            $sorttype = 'ASC';
            
            $this->load->model('msearch');
            $search = $this->msearch->search($select,$table,$where,$sortby,$sorttype,$_GET['page'],5);
            $data['friendlist'] = $search['result'];
            $data['totalpage'] = $search['totalpage'];
            
            $this->design();
            $this->template->title($this->session->userdata('fname').' '.$this->session->userdata('lname').'&rsquo;s Friends - ORPMS');
            $this->template->build('pages/account/friends',$data);        
        }
    }
    
    public function profile() {
        if($this->session->userdata('username')) {
            if(isset($_GET['id'])) {
                $this->load->model('maccount');
                $profile = $this->maccount->getprofile($_GET['id']);
                
                if($profile != null) {
                    $this->load->model('mfriend');
                    $profile['relationship'] = $this->mfriend->getRelationship($this->session->userdata('account_id'),$_GET['id']);
                }
                
                $this->design();
                    
                //Build
                if(isset($_GET['action']) AND $_GET['action']=="update") {
                    $privileges = getprivileges($this->session->userdata('role_id'));
                    if($_GET['id'] == $this->session->userdata('account_id') OR (in_array(6,$privileges) AND $this->session->userdata('level') > $profile['level'])) {
                        if($profile != null) {
                            $this->load->model('mroles');
                            $profile['roles'] = $this->mroles->getRoles();
                        }
                        
                        if($profile != null) {
                            $this->template->title($profile['fname']." ".$profile['lname']." (Edit) - ORPMS");
                        } else {
                            $this->template->title("Profile (Invalid Data) - ORPMS");
                        }
                        
                        $this->template->build('pages/account/updateProfile', $profile);
                    } else {
                        if($profile != null) {
                            $this->template->title($profile['fname']." ".$profile['lname']." - ORPMS");
                        } else {
                            $this->template->title("Profile (Invalid Data) - ORPMS");
                        }
                        $this->template->build('pages/account/profile', $profile);
                    }
                } else {
                    if($profile != null) {
                        $this->template->title($profile['fname']." ".$profile['lname']." - ORPMS");
                    } else {
                        $this->template->title("Profile (Invalid Data) - ORPMS");
                    }
                    $this->template->build('pages/account/profile', $profile);
                }
            } else {
                    redirect(base_url().'account/profile?id='.$this->session->userdata('account_id'));
            }
        } else {
            redirect(base_url().'account/login','refresh');
        }
    }
    
    public function research() {
        if($this->session->userdata('account_id')) {
            $this->design();
            
            if(!isset($_GET['action'])) {
                if(isset($_GET['id'])) {
                    if(!isset($_GET['page'])) {
                        redirect(base_url().'account/research?id='.$this->session->userdata('account_id').'&page=1','refresh');
                    }
                    
                    $select = array('research_id','title','category_name','tbl_research.status','f_name','l_name','tbl_account.account_id','researchers');
                    //$select[5] = "(SELECT GROUP_CONCAT('&nbsp;&nbsp;&nbsp;',name SEPARATOR '<br />') FROM tbl_researcher WHERE research_id=rid) as authors";
                    
                    $table = array('tbl_research','tbl_category','tbl_account','tbl_profile');
                    
                    //if(isset($_GET['keywords']) AND $_GET['searchby'] == 'author') {$table[] = 'tbl_researcher';}
                    
                    //Mark
                    if(isset($_GET['keywords'])) {
                        //$keywords = $_GET['keywords'];
                        $keywords = preg_split('/[\s]+/',$_GET['keywords']);
                        $where[0] = array('tbl_research.category','=','tbl_category.category_id',' AND ');
                        $where[1] = array('tbl_research.account_id','=',$this->session->userdata('account_id'),' AND ');
                        $where[2] = array('tbl_account.account_id','=','tbl_research.account_id',' AND ');
                        $where[3] = array('tbl_profile.profile_id','=','tbl_account.profile_id',' AND ');
                        
                        $count = 4;
                        foreach($keywords as $key) {
                            if(isset($_GET['searchby'])) {
                                switch($_GET['searchby']) {
                                    case 'title':
                                        $field="title";break;
                                    case 'author':
                                        $field="researchers";
                                }
                                $where[$count] = array($field,' LIKE ','\'%'.$key.'%\'',' AND ');
                            } else {
                                $field="title";
                                $where[$count] = array($field,' LIKE ','\'%'.$key.'%\'',' AND ');
                            }
                            $count++;
                        }
                        
                    } else {
                        $where[0] = array('tbl_research.category','=','tbl_category.category_id',' AND ');
                        $where[1] = array('tbl_research.account_id','=',$this->session->userdata('account_id'),' AND ');
                        $where[2] = array('tbl_account.account_id','=','tbl_research.account_id',' AND ');
                        $where[3] = array('tbl_profile.profile_id','=','tbl_account.profile_id',' AND ');
                    }
                    //EndMark
                    
                    if(isset($_GET['sortby'])) {
                        switch($_GET['sortby']) {
                            case 'title':
                                $sortby="title";break;
                            case 'research_id':
                                $sortby="tbl_research.research_id";
                        }
                    } else {
                        $sortby = "title";
                    }
                    
                    if(isset($_GET['sorttype'])) {
                        switch($_GET['sorttype']) {
                            case 'asc':
                                $sorttype="ASC";
                                break;
                            default:
                                $sorttype="DESC";
                        }
                    } else {
                        $sorttype = "DESC";
                    }
                    
                    $this->load->model('msearch');
                    $search = $this->msearch->search($select,$table,$where,$sortby,$sorttype,$_GET['page'],5);
                    $data['researches']= $search['result'];
                    $data['totalpage'] = $search['totalpage'];
                    
                    $this->template->title("Researches - ORPMS");
                    $this->template->build('pages/account/research',$data);
                } else {
                    redirect(base_url().'account/research?id='.$this->session->userdata('account_id'),'refresh');
                }
            } else if ($_GET['action'] == "add") {
                $this->load->model('mcategory');
                $this->load->model('maccesskey');
                $data['categories'] = $this->mcategory->getcategories();
                $data['accesskeys'] = $this->maccesskey->getaccesskey($this->session->userdata('account_id'),2);
                
                $this->template->title("My Researches (Add New) - ORPMS");
                $this->template->build('pages/account/addresearch',$data);
            } else if ($_GET['action'] == "update") {
                if(isset($_GET['part']) AND isset($_GET['id'])) {
                    if($_GET['part'] == 'info') {
                        $this->load->model('mresearch');
                        $this->load->model('mcategory');
                        
                        $data['research'] = $this->mresearch->getresearchinfo($_GET['id']);
                        $data['categories'] = $this->mcategory->getcategories();
                        
                        $this->template->title("My Researches (Update) - ORPMS");
                        $this->template->build('pages/account/updateresearchinfo',$data);
                    } else if($_GET['part'] == 'contents') {
                        $this->load->model('mresearch');
                        $data['sections'] = $this->mresearch->getsections();
                        $data['research'] = $this->mresearch->getresearchinfo($_GET['id']);
                        
                        $this->template->title("My Researches (Update) - ORPMS");
                        $this->template->build('pages/account/updateresearchcontents',$data);
                    }
                } else {
                    redirect(base_url().'account/research?id='.$this->session->userdata('account_id').'&page=1&err=1','refresh');
                }
            }
        } else {
            redirect(base_url().'account/login','refresh');
        }
    }
    
    public function create() {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $conPassword = $_POST['conPassword'];
        $role = $_POST['role'];
        $status = $_POST['status'];
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $gender = $_POST['gender'];
        $birthday = $_POST['birthday'];
        $address = $_POST['address'];
        
        if($_FILES['avatar']['tmp_name']) {
            $avatar = $_FILES['avatar'];
        } else {
            $avatar = null;
        }
        
        if(isset($_POST['about'])) {
            $about = $_POST['about'];
        } else {
            $about = null;
        }
        
        if($username AND $password AND $conPassword AND $role AND isset($status) AND $fname AND $lname AND $gender AND $birthday AND $address) {
            if((strlen($username) > 5 AND strlen($username) < 33) AND (strlen($password) > 5 AND strlen($password) < 33)) {
                if($password == $conPassword) {
                    $this->load->model('maccount');
                    $insert = $this->maccount->create($username,$password,$role,$status,$fname,$lname,$gender,$birthday,$address,$about,$avatar);
                    
                    switch($insert) {
                        case 1:
                            redirect(base_url().'admin/um?action=add&succ=1','refresh');
                            break;
                        case 2:
                            redirect(base_url().'admin/um?action=add&err=3','refresh');
                            break;
                        case 3:
                            redirect(base_url().'admin/um?action=add&err=4','refresh');
                            break;
                        case 4:
                            redirect(base_url().'admin/um?action=add&err=5','refresh');
                    }
                } else {
                    redirect(base_url().'admin/um?action=add&err=2','refresh');//Failure in confirming password
                }
            } else {
                redirect(base_url().'admin/um?action=add&err=6','refresh');//Username and Password must be between 6-32 characters
            }
        } else {
            redirect(base_url().'admin/um?action=add&err=1','refresh');//Please fill in all required fields
        }
    }
    
    public function updateProfile() {
        $id = $_POST['id'];
        $oUsername = $_POST['oUsername'];
        $username = $_POST['username'];
        $role = $_POST['role'];
        $status = $_POST['status'];
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $gender = $_POST['gender'];
        $birthday = $_POST['birthday'];
        $address = $_POST['address'];
        
        if($_FILES['avatar']['tmp_name']) {
            $avatar = $_FILES['avatar'];
        } else {
            $avatar = null;
        }
        
        if(isset($_POST['about'])) {
            $about = $_POST['about'];
        } else {
            $about = null;
        }
        
        if($id AND $oUsername AND $username AND $role AND isset($status) AND $fname AND $lname AND $gender AND $birthday AND $address) {
            if(isset($_POST['editPassword'])) {
                if(isset($_POST['oldPassword'])) {
                    $oldPassword = $_POST['oldPassword'];
                } else {
                    $oldPassword = null;
                }
                $newPassword = $_POST['newPassword'];
                $conPassword = $_POST['conPassword'];
                
                if((strlen($username) > 5 AND strlen($username) < 33) AND (strlen($newPassword) > 5 AND strlen($newPassword) < 33)) {                     
                    if(($oldPassword AND $newPassword AND $conPassword) OR (!$oldPassword AND $this->session->userdata('account_id') != $id)) {
                        if($newPassword == $conPassword) {
                            $this->load->model('maccount');
                            $update = $this->maccount->update($id,$oUsername,$username,$oldPassword,$newPassword,$role,$status,$fname,$lname,$gender,$birthday,$address,$about,$avatar);
                            if($update == 3) {
                                redirect(base_url().'account/profile?action=update&id='.$id.'&err=3','refresh');//Invalid Old Password
                            } else if($update == 2) {
                                redirect(base_url().'account/profile?action=update&id='.$id.'&err=4','refresh');//Something went wrong
                            } else if($update == 4) {
                                redirect(base_url().'account/profile?action=update&id='.$id.'&err=5','refresh');//Username already exists
                            } else if($update == 5) {
                                redirect(base_url().'account/profile?action=update&id='.$id.'&err=7','refresh');//Username already exists
                            } else if($update == 1) {
                                if($id == $this->session->userdata('account_id')) {
                                    $userdata = array(
                                        'username' => $username,
                                        'fname' => $fname,
                                        'lname' => $lname,
                                        'gender' => $gender,
                                        'birthay' => $birthday
                                    );
                                    $this->session->set_userdata($userdata);
                                }
                                redirect(base_url().'account/profile?id='.$id.'&succ=1','refresh');//Success
                            }
                        } else {
                            redirect(base_url().'account/profile?action=update&id='.$id.'&err=2','refresh');//Failed confirming the new password
                        }
                    } else {
                        redirect(base_url().'account/profile?action=update&id='.$id.'&err=1','refresh');//Please fill in all required fields
                    }    
                } else {
                    redirect(base_url().'account/profile?action=update&id='.$id.'&err=6','refresh');//Username and Password must be between 6-32 characters    
                }
            } else {
                if(strlen($username) > 5 AND strlen($username) < 33) {
                    $this->load->model('maccount');
                    $update = $this->maccount->update($id,$oUsername,$username,null,null,$role,$status,$fname,$lname,$gender,$birthday,$address,$about,$avatar);
                    if($update == 1) {
                        if($id == $this->session->userdata('account_id')) {
                            $userdata = array(
                                'username' => $username,
                                'role_id' => $role,
                                'status' => $status,
                                'fname' => $fname,
                                'lname' => $lname,
                                'gender' => $gender,
                                'birthay' => $birthday
                            );
                            $this->session->set_userdata($userdata);
                        }
                        redirect(base_url().'account/profile?id='.$id.'&succ=1','refresh');//Success
                    } else if($update == 5) {
                        redirect(base_url().'account/profile?action=update&id='.$id.'&err=7','refresh');//Something went wrong
                    } else if($update == 2) {
                        redirect(base_url().'account/profile?action=update&id='.$id.'&err=4','refresh');//Something went wrong
                    } else if($update == 4) {
                        redirect(base_url().'account/profile?action=update&id='.$id.'&err=5','refresh');//Username already exists
                    }
                } else {
                        redirect(base_url().'account/profile?action=update&id='.$id.'&err=6','refresh');//Username and Password must be between 6-32 characters                 
                }
            }
        } else {
            redirect(base_url().'account/profile?action=update&id='.$id.'&err=1','refresh');//Please fill in all required fields
        }
    }
    
    public function checkuser() {
        $username = $_POST['username'];
        $password = $_POST['password'];
        
        $this->load->model('maccount');
        $user = $this->maccount->checkuser($username,$password);
        
        switch($user) {
            case 1:
                redirect(base_url().'account/login?err=1','refresh');
                break;
            case 2:
                redirect(base_url().'account/login?err=2','refresh');
                break;
            default:
                $this->session->set_userdata($user);
                redirect(base_url().'account/profile','refresh');die();
        }
    }
    
    public function getavatar($id) {
        if($this->session->userdata('username')) {
            $this->load->model('maccount');
            $avatar = $this->maccount->getavatar($id);
            $image = $avatar[0]->avatar;
            
            header("Content-type: image/jpeg");
            
            echo $image;   
        } else {
            redirect(base_url().'account/login','refresh');
        }
    }
    
    public function logout() {
        $this->session->sess_destroy();                         
        redirect(base_url().'account/login','refresh');
    }
}